package com.ay.smartpark.sdk.common.utils;

import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

public class JsonArrayUtils {


    /**
     * 从jsonArray转为带逗号的字符串
     * @return
     */
    public static String getJsonArrayToSpiltStr(String jsonArrayStr){
        String result = "";
        if(StringUtils.isNotBlank(jsonArrayStr)) {
            JSONArray jsonArray = JSONArray.parseArray(jsonArrayStr);
            if (!jsonArray.isEmpty()) {
                List<String> jsonArrayList = jsonArray.toJavaList(String.class);
                StringBuffer stringBuffer = new StringBuffer();
                for (String value : jsonArrayList) {
                    stringBuffer.append(value);
                    stringBuffer.append(",");
                }
                if(StringUtils.isNotBlank(stringBuffer)){
                    stringBuffer.delete(stringBuffer.length() - 1, stringBuffer.length());
                }

                result = stringBuffer.toString();
            }
        }
        return result;
    }

    /**
     * 已经存在且不为空的JsonArray新增元素
     */
    public static String getJsonArrayAdditionalStr(String jsonArrayStr,String value){
        JSONArray jsonArray = JSONArray.parseArray(jsonArrayStr);
        jsonArray.add(value);
        return jsonArray.toString();
    }


    /**
     * 把带有','的字符串转为jsonArray字符串
     */
    public static String getJsonArrayStr(String value){
        JSONArray jsonArray = new JSONArray();
        String charStr = ",";
        if(value.contains(charStr)){
            String[] valueArray = value.split(",");
            for (String str : valueArray) {
                jsonArray.add(str);
            }
        } else {
            jsonArray.add(value);
        }
        return jsonArray.toString();
    }





    /**
     * 把一个元素放到JsonArray数组中
     */
    public static String addValueToNewJsonArray(String value){
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(value);
        return jsonArray.toString();
    }




}
